﻿/*
 * Copyright 2012 Rene Prost, Registrite ja Infosüsteemide Keskus 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using Calculator.Xroad.Eu;
using Calculator.Xroad.Eu.Messages;
using Doc.Xroad.Eu.Messages;
using NUnit.Framework;
 
using Xtee.Core.Client;
using Xtee.Core.Client.Config;
using Xtee.Core.Envelope;
using Xtee.Core.Envelope.Header;
using Xtee.Core.Mime.Message;

namespace Xtee.Core.Test
{
    [TestFixture]
    public class SoapRequestTest
    {
        public static string ADAPTERADDR = "http://localhost:6005/adapter.asmx";

        public static IHeader Header = null; 


        [Test]
        public  void Test()
        {
            IXteeClientConfiguration clientConfiguration = GetTestConf();
            
            IXteeSoapRequest request = new XteeSoapRequest(clientConfiguration);
            ISoapHttpResponse response = request.RunSoap(new SoapEnvelope("na", Header, new AddRequest(new Variables(1,1)))); 
            using (response)
            {
                var reader = new StreamReader(response.GetResponseSoapMessage().GetEnvelope());
                string data = reader.ReadToEnd();

                reader.Close();
                Console.WriteLine(data);
            }
                 
        }

        private IXteeClientConfiguration GetTestConf()
        {

            return new Configuration
            {
                ProxyURL = new Uri(ADAPTERADDR),
                Debug = 0,
                //StoreRequest = true,
                //StoreResponse = true,
                Storage =
                               new Storage(null, false, @"../../ResourceData/StoredMessages/", Environment.GetEnvironmentVariable("TEMP"))
            };
        }

        [Test]
        public void TestThat_SoapHttpRequestAndSoapHttpResponse_GetsDisposed()
        {
            DateTime now = DateTime.Now;
            ISoapHttpRequest request = SoapHttpRequest.Create(ADAPTERADDR, new Storage(null,false,@"../../ResourceData/StoredMessages/", Environment.GetEnvironmentVariable("TEMP")),null);
            using (Stream stream = File.OpenRead(@"..\..\ResourceData\CreateMessage.eml"))
            {
                using (request)
                {
                    request.GetRequestSoapMessage().LoadMessage(stream);
                    ISoapHttpResponse resp = request.GetResponse();
                    using (resp)
                    {
                        StreamReader reader = new StreamReader(resp.GetResponseSoapMessage().GetEnvelope());
                        string data = reader.ReadToEnd();
                    }

                    try
                    {
                        resp.GetResponseSoapMessage();
                    }
                    catch (Exception ex)
                    {
                        Assert.That(ex is ObjectDisposedException);
                    }
                   
                }
                try
                {
                    request.GetRequestSoapMessage();
                }
                catch (Exception ex)
                {
                    Assert.That(ex is ObjectDisposedException);
                }
                 
            }
        }
        [Test]
        public void TestThat_XteeSoapRequest_GetsDisposed()
        {
            IXteeClientConfiguration clientConfiguration = GetTestConf();

            IXteeSoapRequest request = new XteeSoapRequest(clientConfiguration);
            ISoapHttpResponse response = request.RunSoap(new SoapEnvelope("na",Header, new AddRequest(new Variables(1, 1))));
            using (response)
            {
                StreamReader reader = new StreamReader(response.GetResponseSoapMessage().GetEnvelope());
                using(reader)
                    Console.WriteLine(reader.ReadToEnd()); 
            } 

        }
        [Test]
        public void TestThat_SoapRquest_RunSoap_CanbeCalledManyTimes()
        {
            IXteeClientConfiguration clientConfiguration = GetTestConf();

            IXteeSoapRequest request = new XteeSoapRequest(clientConfiguration);
            for(int x=0;x<=3;x++)
            {
                ISoapHttpResponse response = request.RunSoap(new SoapEnvelope("na", Header, new AddRequest(new Variables(1, 1))));
                using (response)
                {
                    StreamReader reader = new StreamReader(response.GetResponseSoapMessage().GetEnvelope());
                    using (reader)
                        Console.WriteLine(reader.ReadToEnd());
                }  
            }
           
        }

        private string xml =
            @"<?xml version='1.0' encoding='utf-8'?>
<SOAP-ENV:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'  xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:tns='http://calculator.x-road.eu' xmlns:xrd='http://x-road.eu/xsd/xroad.xsd' xmlns:id='http://x-road.eu/xsd/identifiers'><SOAP-ENV:Header>
  <xrd:client id:objectType='SUBSYSTEM'>
    <id:xRoadInstance>ee-dev</id:xRoadInstance>
    <id:memberClass>GOV</id:memberClass>
    <id:memberCode>70000310</id:memberCode>
    <id:subsystemCode>generic-consumer</id:subsystemCode>
  </xrd:client>
  <xrd:service id:objectType='SERVICE'>
    <id:xRoadInstance>EE</id:xRoadInstance>
    <id:memberClass>GOV</id:memberClass>
    <id:memberCode>700030</id:memberCode>
    <id:subsystemCode>Calc</id:subsystemCode>
    <id:serviceCode>Add</id:serviceCode>
    <id:serviceVersion>v1</id:serviceVersion>
  </xrd:service>
  <xrd:id>411d6755661409fed365ad8135f8210be07613da</xrd:id>
  <xrd:userId>EE39010210022</xrd:userId>
  <xrd:protocolVersion>4.0</xrd:protocolVersion>
</SOAP-ENV:Header><SOAP-ENV:Body><tns:Add>
  <request>
    <VarX>1</VarX>
    <VarY>1</VarY>
  </request>
</tns:Add></SOAP-ENV:Body></SOAP-ENV:Envelope>";

        private string xml2 =
                    "<?xml version='1.0' encoding=\"utf-8\"?>\r\n<SOAP-ENV:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"  xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Header><andmekogu xsi:type=\"xsd:string\">Calc</andmekogu><nimi xsi:type=\"xsd:string\">calc.simple_calc.v2</nimi></SOAP-ENV:Header><SOAP-ENV:Body><docalc><keha></keha></docalc></SOAP-ENV:Body></SOAP-ENV:Envelope>";

        [Test]
        public void SoapHttpRequestTestService()
        {
            DateTime now = DateTime.Now;
            ISoapHttpRequest request = SoapHttpRequest.Create(ADAPTERADDR, new Storage(null,false,@"../../ResourceData/StoredMessages/", Environment.GetEnvironmentVariable("TEMP")),null);
            using(request)
            {
                request.SetEnvelope(new MemoryStream(Encoding.UTF8.GetBytes(xml2))); 
                ISoapHttpResponse resp = request.GetResponse();
                using(resp)
                {
                    StreamReader reader = new StreamReader(resp.GetResponseSoapMessage().GetEnvelope());

                    string data = reader.ReadToEnd();
                    Console.WriteLine(DateTime.Now - now);
                    Console.WriteLine(data);
                } 
                
            }
            

        }
        [Test]
        public void SoapHttpRequestLoadFromFile()
        {
          
            DateTime now = DateTime.Now;
            ISoapHttpRequest request = SoapHttpRequest.Create(ADAPTERADDR, new Storage(null, false, @"../../ResourceData/StoredMessages/", Environment.GetEnvironmentVariable("TEMP")),null);
            using (request) 
            using (Stream stream = File.OpenRead(@"..\..\ResourceData\CreateMessage.eml"))
            { 

                request.GetRequestSoapMessage().LoadMessage(stream);
                ISoapHttpResponse resp = request.GetResponse();
                using(resp)
                {
                    StreamReader reader = new StreamReader(resp.GetResponseSoapMessage().GetEnvelope());
                    string data = reader.ReadToEnd();
                    Console.WriteLine(data);
                }
             
               
               
            }
            
        }
      
        [Test]
        public void SoapHttpRequestTestBackedWithFile()
        {
            DateTime now = DateTime.Now;
            ISoapHttpRequest request = SoapHttpRequest.Create(ADAPTERADDR, new Storage(null, false, @"../../ResourceData/StoredMessages/", Environment.GetEnvironmentVariable("TEMP")), null);
            using(request)
            {
                request.SetEnvelope(new MemoryStream(Encoding.UTF8.GetBytes(xml)));

                using (FileStream str = File.Open(Environment.GetEnvironmentVariable("TEMP") + "\\SoapHttpRequestTest.xml", FileMode.Create, FileAccess.ReadWrite))
                    request.SaveRequest(str);

                ISoapHttpResponse resp = request.GetResponse();
                using(resp)
                {
                    using (FileStream str = File.Open(Environment.GetEnvironmentVariable("TEMP") + "\\SoapHttpResponseTest.xml", FileMode.Create, FileAccess.ReadWrite))
                        resp.SaveResponse(str);
                    StreamReader reader = new StreamReader(resp.GetResponseSoapMessage().GetEnvelope());
                    string data = reader.ReadToEnd();
                    Console.WriteLine(DateTime.Now - now);
                    Console.WriteLine(data);
 
                    Assert.IsTrue(File.ReadAllText(Environment.GetEnvironmentVariable("TEMP") + "\\SoapHttpRequestTest.xml").
                        Contains(@"Content-Type: text/xml; charset=UTF-8
Content-Transfer-Encoding: 8bit
SOAPAction: 
Mime-Version: 1.0

<?xml version='1.0' encoding='utf-8'?>
<SOAP-ENV:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'  xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:tns='http://calculator.x-road.eu' xmlns:xrd='http://x-road.eu/xsd/xroad.xsd' xmlns:id='http://x-road.eu/xsd/identifiers'><SOAP-ENV:Header>
  <xrd:client id:objectType='SUBSYSTEM'>
    <id:xRoadInstance>ee-dev</id:xRoadInstance>
    <id:memberClass>GOV</id:memberClass>
    <id:memberCode>70000310</id:memberCode>
    <id:subsystemCode>generic-consumer</id:subsystemCode>
  </xrd:client>
  <xrd:service id:objectType='SERVICE'>
    <id:xRoadInstance>EE</id:xRoadInstance>
    <id:memberClass>GOV</id:memberClass>
    <id:memberCode>700030</id:memberCode>
    <id:subsystemCode>Calc</id:subsystemCode>
    <id:serviceCode>Add</id:serviceCode>
    <id:serviceVersion>v1</id:serviceVersion>
  </xrd:service>
  <xrd:id>411d6755661409fed365ad8135f8210be07613da</xrd:id>
  <xrd:userId>EE39010210022</xrd:userId>
  <xrd:protocolVersion>4.0</xrd:protocolVersion>
</SOAP-ENV:Header><SOAP-ENV:Body><tns:Add>
  <request>
    <VarX>1</VarX>
    <VarY>1</VarY>
  </request>
</tns:Add></SOAP-ENV:Body></SOAP-ENV:Envelope>"));

                    Assert.IsTrue(data.Contains("<Result><Value>2</Value></Result>"));
                }
               
            }
            

        }
        [Test]
        public void SoapHttpRequestTestInMemory()
        {
            DateTime now = DateTime.Now;
            ISoapHttpRequest request = SoapHttpRequest.Create(ADAPTERADDR, new Storage(null, false, @"../../ResourceData/StoredMessages/", Environment.GetEnvironmentVariable("TEMP")),null);
            using(request)
            {
                request.SetEnvelope(new MemoryStream(Encoding.UTF8.GetBytes(xml)));
                request.GetRequestSoapMessage().GetEnvelope().Position = 0;
                string requestenvelope = new StreamReader(request.GetRequestSoapMessage().GetEnvelope()).ReadToEnd();
                
                ISoapHttpResponse resp = request.GetResponse();
                using(resp)
                {
                    StreamReader reader = new StreamReader(resp.GetResponseSoapMessage().GetEnvelope());
                    string data = reader.ReadToEnd();
                    Console.WriteLine(DateTime.Now - now);
                    Console.WriteLine(data);

                    Assert.AreEqual(requestenvelope, xml);

                    Assert.IsTrue(data.Contains("<Result><Value>2</Value></Result>"));
                    
                }
              

           
            }
         

          
        }

        [Test]
        public void SoapRequestSaveTest()
        {
            DateTime now = DateTime.Now;
            ISoapHttpRequest request = SoapHttpRequest.Create(ADAPTERADDR, new Storage(null, false, @"../../ResourceData/StoredMessages/", Environment.GetEnvironmentVariable("TEMP")),null);
            using(request)
            using (FileStream str = File.Open(Environment.GetEnvironmentVariable("TEMP") + "\\tmptmp.xml", FileMode.Create, FileAccess.ReadWrite))
            {
                    request.SaveRequest(str);

            }
            File.Delete(Environment.GetEnvironmentVariable("TEMP") + "\\tmptmp.xml");
            Console.WriteLine(DateTime.Now - now);
            
        }

        [Test]
        public void SoapRequestMesage()
        {
            DateTime now = DateTime.Now;
            ISoapHttpRequest request = SoapHttpRequest.Create(ADAPTERADDR, new Storage(null, false, @"../../ResourceData/StoredMessages/", Environment.GetEnvironmentVariable("TEMP")), null);
            using(request)
            {
                ISoapMessage message = request.GetRequestSoapMessage(); 
                Assert.IsNotNull(message);
                Console.WriteLine(DateTime.Now - now);
            }
           
            
        }
 

    }
    

     
}
